import requests

import re



# login_url = 'http://127.0.0.1:8000/admin/login/?next=/admin/'
# # 发起get请求获取隐藏域csrf_token 和 cookie
# response = requests.get(login_url)
# # print(response.text)
# coike = response.cookies.get_dict()
# csrf_token = re.findall(r'name="csrfmiddlewaretoken" value="(.*?)"',response.text)[0]
# # print(csrf_token)
#
#
# data = {
# 	'csrfmiddlewaretoken': csrf_token,
# 	'username': 'admin',
# 	'password': '123456'
# }
# response = requests.post(login_url,data=data,cookies=coike)
# print(response.status_code)
# print(response.text)


# 使用会话 session 会携带所有的 cookie

session = requests.session()
login_url = 'http://127.0.0.1:8000/admin/login/?next=/admin/'
response = session.get(login_url)
csrf_token = re.findall(r'name="csrfmiddlewaretoken" value="(.*?)"',response.text)[0]
data = {
	'csrfmiddlewaretoken': csrf_token,
	'username': 'admin',
	'password': '123456'
}
response = session.post(login_url,data=data)
print(response.status_code)
print(response.text)